package cn.sc.summer.calculate.service.impl;

import cn.sc.summer.calculate.property.ServerScoreProperties;
import cn.sc.summer.constant.rabbit.RabbitConstant;
import cn.sc.summer.constant.redis.RedisConstant;
import cn.sc.summer.rabbitmq.enums.RabbitErrorMessageTypeEnum;
import cn.sc.summer.rabbitmq.po.RabbitMessage;
import cn.sc.summer.rabbitmq.service.RabbitConsumerService;
import cn.sc.summer.rabbitmq.util.RabbitUtil;
import cn.sc.summer.redis.util.RedisHelper;
import cn.sc.summer.system.po.SystemInfoDTO;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 类名：服务器资源信息处理业务层
 *
 * @author a-xin
 * @date 2024/1/26 16:02
 */
@Slf4j
@Service
public class ServerSystemInfoServiceImpl extends RabbitConsumerService {

    @Resource
    private ServerScoreProperties serverScoreProperties;

    /**
     * 接口: 监听服务转发的服务器资源信息，并做入库处理
     *
     * @param jsonStr 日志信息
     * @param message rabbit消息提
     * @param channel rabbit
     * @author a-xin
     * @date 2023/9/23 15:48
     */
    @RabbitListener(queues = RabbitConstant.SERVER_SYSTEM_INFO_QUEUE)
    public void consumer(String jsonStr, Message message, Channel channel) {
        try {
            RabbitMessage<SystemInfoDTO> sysSystemInfoRabbitMessage = RabbitUtil.checkMessage(jsonStr, new TypeReference<SystemInfoDTO>() {
            });
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            if (sysSystemInfoRabbitMessage.getFlag()) {
                addSystemInfo(sysSystemInfoRabbitMessage.getMessage());
            } else {
                log.error("==> 接收到重复消费消息：Queue: {}, Exchange : {}, RoutingKey : {}, Message : {}",
                        RabbitConstant.SERVER_SYSTEM_INFO_QUEUE,
                        RabbitConstant.SERVER_SYSTEM_INFO_EXCHANGE,
                        RabbitConstant.SERVER_SYSTEM_INFO_ROUTING_KEY,
                        jsonStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
            rabbitErrorService.exchangeMessage(e.getMessage(), jsonStr, RabbitErrorMessageTypeEnum.SERVER_SYSTEM_INFO_WRITE_ERROR);
        }
    }

    /**
     * 将服务发送的消息进行存储
     *
     * @param sysSystemInfo 服务抓取的服务器信息
     */
    protected void addSystemInfo(SystemInfoDTO sysSystemInfo) {
        String redisKey = RedisConstant.SERVER_SYSTEM_INFO + sysSystemInfo.getServerNamespace() + ":" + sysSystemInfo.getServerIp() + ":" + sysSystemInfo.getServerPort();
        Long length = RedisHelper.lAdd(redisKey, JSONObject.toJSONString(sysSystemInfo));
        if (length > serverScoreProperties.getNumber()) {
            RedisHelper.lTrim(redisKey, 0L, Long.valueOf(serverScoreProperties.getNumber()));
        }
    }

}
